﻿using System.Collections.Generic;
using Kugar.Core.Web;
using Microsoft.AspNetCore.Http;

namespace Kugar.Tool.Web.RequestFieldValidation
{
    public class RequestField<T>: IRequestField<T>
    {
        private List<IRule> _rules=new List<IRule>();
        private HttpRequest _request = null;
        private T _inputValue;

        internal RequestField(string fieldName,T inputValue, HttpRequest request,string format, string title)
        {
            Request = request;
            FieldName = fieldName;
            Format = format;
            Title = title;
            _inputValue = inputValue;
            StringValue = request.GetString(fieldName, null);
        }

        public HttpRequest Request { get; }

        public string FieldName { get; }

        public string Title { get;}

        public string Format { get; }

        public string StringValue { get; }

        public IEnumerable<IRule> Rules => _rules;

        public T Value()
        {
            return _inputValue;
        }

        public void AddRule(IRule rule)
        {
            _rules.Add(rule);
            
        }

        public bool IsValid
        {
            get
            {
                foreach (var rule in _rules)
                {
                    if (!rule.Validate(this))
                    {
                        return false;
                    }
                }

                return true;
            }
        }

        public static implicit operator T(RequestField<T> d)
        {
            return d._inputValue;
        }

        public static RequestField<TValue> FromValue<TValue>(string fieldName, TValue value, HttpRequest request=null,
            string title="")
        {
            return new RequestField<TValue>(fieldName,value,request??Kugar.Core.Web.HttpContext.Current.Request,"",title);
        }
    }
}